﻿var autoComplete = {
    selectIndex: 0,     //当前选择的数据索引值
    aryLength: 0,      //检索出的数据大小
    InputId: null,        //文本控件Id
    divDiseaseTypeId: null,   //文本外层DIV
    resultDivId: null,     //返回结果列表DIV
    ClickDeleteIsOK: false,   // 是否单击删除
    validateEvent: false,  //由于事件 mouseover 和 keyUp event keyCode(38/40)冲突  定义变量初始化鼠标可以选择结果项。
    badChar: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 　`~!@#$%^&()-_=+]\\|:;\"\'<,>?/",  //根据字符来判断文本框宽度的大小
    requestPath: null,  //请求路径
    init: function (DivControlId, InputControlId, RequestPath) {
        
        this.InputId = InputControlId;
        this.divDiseaseTypeId = DivControlId;
        this.requestPath = RequestPath;

        var divResult = $("<div id='divResultId' class='ItemList'><ul></ul></div>");
        $("#" + this.divDiseaseTypeId).after(divResult);
        this.resultDivId = "divResultId";

        //帮文本框绑定keydown键盘按下、keyup键盘松下、blur、失去焦点事件
        $("#" + this.InputId + "").bind("keydown", function (event) {
            autoComplete.keyEventObj(event);      //调用键盘监听函数
        }).bind("keyup", function () {
            autoComplete.display();    //检查输入完成自动完成函数
            return false;
        }).bind("blur", function () {
            autoComplete.keySetValue();  //调用失去焦点帮文本框至包括下来
            autoComplete.closeControl(autoComplete.resultDivId);    //关闭数据选择
            $("#" + autoComplete.divDiseaseTypeId + " div").removeClass("ChooseDiv");
        });
        $("#" + this.divDiseaseTypeId).bind("click", function () {
            $("#" + autoComplete.divDiseaseTypeId + " div").removeClass("ChooseDiv");
            $("#" + autoComplete.InputId).focus();
        });
    },
    setClickDeleteIsOK: function (ClickDeleteIsOK) {
        this.ClickDeleteIsOK = ClickDeleteIsOK;
    },
    displayControl: function (ControlId) { $("#" + ControlId).css("display", "block"); }, //显示控件
    closeControl: function (ControlId) { $("#" + ControlId).css("display", "none"); }, //隐藏控件
    display: function () {                            //显示输入检索方法
        var JI = $("#" + this.InputId).val();
        var inputWidth = 1;
        if ($.trim(JI) != null && $.trim(JI) != "") {
            inputWidth = this.getWidth(JI);
            this.ajaxRequestData();
        } else {
            this.closeControl(this.resultDivId);
        }
        $("#" + this.InputId).width(inputWidth + "px");
    },
    getWidth: function (str) {
        var charIndex = 0;
        var inputWidth = 0;
        for (var i = 0; i < str.length; i++) {
            var c = str.charAt(i);
            if (this.badChar.indexOf(c) > -1) {
                inputWidth = inputWidth + 8;
                charIndex++;
            }
        }
        inputWidth = inputWidth + ((str.length - charIndex) * 14);
        return inputWidth;
    },
    ajaxRequestData: function () {   //根据输入的字节 请求数据方法
        var keywords = $("#" + autoComplete.InputId).val();
        var dataUrl = "keywords=" + escape(keywords) + "&DataTime=" + new Date().getTime();
        $.ajax({
            type: "post",
            url: this.requestPath, //
            dataType: "json",
            data: dataUrl,
            success: function (msg) {
                $("#" + autoComplete.resultDivId + " ul").html("");
                if (msg.rows.length > 0) {
                    for (var i = 0; i < msg.rows.length; i++) {
                        $("#" + autoComplete.resultDivId + " ul").append("<li title='" + msg.rows[i].ID + "'>" + msg.rows[i].NAME + "</li>");
                    }
                    $("#" + autoComplete.resultDivId + " li:eq(" + autoComplete.selectIndex + ")").addClass("selectd");
                    autoComplete.aryLength = msg.rows.length;
                    $("#" + autoComplete.resultDivId + " li").bind("mouseover", function () {
                        if (!autoComplete.validateEvent) {     //验证键盘是否在启用上下操作。
                            autoComplete.selectIndex = parseInt($(this).index());
                            autoComplete.addSelectStyle();
                        }
                    }).bind("mouseout", function () {
                        autoComplete.validateEvent = false;
                    }).unbind("mousedown").bind("mousedown", function () {
                        autoComplete.selectVal();
                        autoComplete.closeControl(autoComplete.resultDivId);
                        setTimeout(function () { $("#" + autoComplete.InputId).focus(); }, 100);
                    });
                    autoComplete.displayControl(autoComplete.resultDivId);
                } else {
                    autoComplete.closeControl(autoComplete.resultDivId);
                }
            },
            error: function () {
                alert("出现错误");
            }
        });
    },
    selectVal: function () {   //设置值
        var Value = $("#" + this.InputId).val();
        if (Value != "" && Value != null) {
            var text = $("#" + this.resultDivId + " li:eq(" + this.selectIndex + ")").text();  //选中值
            if (text != null && text != "") {
                var DiseaseId = $("#" + this.resultDivId + " li:eq(" + this.selectIndex + ")").attr("title"); //选中值的ID
                this.SetValue(DiseaseId, text);
            } else {
                this.SetValue("", Value);
            }
        }
    },
    selectDivEvent: function (div) {
        div.bind("mouseout", function () {
            if (!$(this).hasClass("ChooseDiv")) { $(this).removeClass("SelectChooseDiv"); }
        }).bind("mouseover", function () {
            if (!$(this).hasClass("ChooseDiv")) { $(this).addClass("SelectChooseDiv"); }
        }).bind("click", function () {
            if (autoComplete.ClickDeleteIsOK) {
                $(this).remove();
            } else {
                $("#" + autoComplete.divDiseaseTypeId + " div").removeClass("ChooseDiv");
                $(this).removeClass("SelectChooseDiv").addClass("ChooseDiv");
                autoComplete.keySetValue();
                autoComplete.closeControl(autoComplete.resultDivId);
                $(this).find("input").focus().bind("keydown", function (event) { autoComplete.keyEventObj(event); });
                return false;
            }
        }).bind("dblclick", function () {
            $(this).after($("#" + autoComplete.InputId));
            var fss = $(this).text();
            var DiseaseId = $(this).attr("DiseaseId");
            $(this).remove();
            $("#" + autoComplete.InputId).val(fss);  //读取当前数据
            $("#" + autoComplete.InputId).unbind("blur").bind("blur", function () {
                var newtxt = $("#" + autoComplete.InputId).val();  //读取新数据
                if (newtxt == "") return false;
                if (fss != newtxt) {
                    $("#" + autoComplete.InputId).removeAttr("CurDiseaseld");
                } else {
                    $("#" + autoComplete.InputId).attr("CurDiseaseld", DiseaseId);
                }
                autoComplete.keySetValue();
                autoComplete.closeControl(autoComplete.resultDivId);
            });
            var inputWidth = autoComplete.getWidth(fss);
            $("#" + autoComplete.InputId).width(inputWidth + "px");
            $("#" + autoComplete.InputId).focus();
            return false;
        });

        div.find("input").unbind("click").bind("click", function () {
            $("#" + autoComplete.divDiseaseTypeId + " div").removeClass("ChooseDiv");
            div.before($("#" + autoComplete.InputId));
            $(this).blur();
            $("#" + autoComplete.InputId).focus();
            return false;
        });
    },
    SetValue: function (Diseaseld, text) {
        text = text.replace(";", "") + ";";
        this.checkValue(text);
        if (text != null && text != "") {
            var div = $("<div class='ChooseValue' ><input type='text' tabindex='-1' style='  background-color:transparent;width:1px; border:0px;'/>" + text + "</div>");
            if (typeof (Diseaseld) != "undefined" && Diseaseld != "")
                div.attr("DiseaseId", Diseaseld);
            else
                div.addClass("inputError");

            $("#" + this.InputId).val("").width("5px").before(div);
            this.selectDivEvent(div);
        }
    },
    keySetValue: function () {
        var Value = $("#" + this.InputId).val();
        var CurDiseaseld = $("#" + this.InputId).attr("CurDiseaseld");
        //$("#divRecord").append(CurDiseaseld + "");
        if (Value != "" && Value != null) {
            this.SetValue(CurDiseaseld, Value);
        }
    },
    checkValue: function (str) {     //检查是否有重复值，如果存在删除
        $("#" + this.divDiseaseTypeId + " div").each(function () {
            var txt = $(this).text();
            if (txt == str) {
                $(this).remove();
            }
        });
    },
    addSelectStyle: function () {
        $("#" + this.resultDivId + " li").removeClass("selectd").eq(this.selectIndex).addClass("selectd");
    },
    keyEventObj: function (event) {
        var e = event ? event : (window.event ? window.event : null);
        var txt = $("#" + this.InputId).val();
        switch (e.keyCode) {
            case 37:      //左键
                if (txt == "") {
                    $("#" + this.divDiseaseTypeId + " div").removeClass("ChooseDiv");
                    $("#" + this.InputId).prev().before($("#" + this.InputId));
                    $("#" + this.InputId).select();
                    this.keySetValue();
                }
                break;
            case 38:      //上键
                if (this.selectIndex > 0) { this.selectIndex--; } else { this.selectIndex = this.aryLength - 1; }
                this.addSelectStyle();
                this.validateEvent = true;
                break;
            case 39:     //右键
                if (txt == "") {
                    $("#" + this.divDiseaseTypeId + " div").removeClass("ChooseDiv");
                    $("#" + this.InputId).next().after($("#" + this.InputId));
                    $("#" + this.InputId).select();
                    this.keySetValue();
                }
                break;
            case 40:     //下键
                if (this.selectIndex >= this.aryLength - 1) { this.selectIndex = 0; } else { this.selectIndex++; }
                this.addSelectStyle();
                this.validateEvent = true;
                break;
            case 13:     //enter
                this.selectVal();
                break;
            case 8:       //backspace
                var Flag = false;
                var Num = 0;
                if (txt == "") {
                    $("#" + this.divDiseaseTypeId + " div").each(function () {
                        if ($(this).hasClass("ChooseDiv")) { $(this).remove(); Flag = true; }
                    });
                    if (!Flag) {
                        $("#" + this.InputId).prev().addClass("ChooseDiv");
                        $("#" + this.InputId).focus();
                    }
                }
                return false;
                break;
        }
        return false;
    }
};
